{% extends "base.html" %}

{% block title %}用户管理 - {{ app_name }}{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>
                <i class="fas fa-users me-2"></i>
                用户管理
            </h2>
            <div>
                <a href="/admin" class="btn btn-outline-secondary me-2">
                    <i class="fas fa-arrow-left me-2"></i>返回后台
                </a>
                <button type="button" class="btn btn-info me-2" data-bs-toggle="modal" data-bs-target="#importUserModal">
                    <i class="fas fa-upload me-2"></i>
                    导入数据
                </button>
                <button type="button" class="btn btn-success me-2" onclick="exportUsers()">
                    <i class="fas fa-download me-2"></i>
                    导出数据
                </button>
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createUserModal">
                    <i class="fas fa-user-plus me-2"></i>
                    创建用户
                </button>
            </div>
        </div>
        
        <!-- 用户列表 -->
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-light">
                <h5 class="mb-0">用户列表</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0" id="usersTable">
                        <thead class="table-light">
                            <tr>
                                <!--<th>ID</th>-->
                                <th>用户名</th>
                                <th>手机号</th>
                                <th>邮箱</th>
                                <th>角色</th>
                                <th>状态</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- 数据将通过JavaScript加载 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 创建用户模态框 -->
<div class="modal fade" id="createUserModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-user-plus me-2"></i>
                    创建新用户
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="createUserForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="username" class="form-label">用户名 *</label>
                        <input type="text" class="form-control" id="username" name="username" required>
                    </div>
                    <div class="mb-3">
                        <label for="password" class="form-label">密码 *</label>
                        <div class="input-group">
                            <input type="password" class="form-control" id="password" name="password" required>
                            <button class="btn btn-outline-secondary" type="button" id="generatePasswordBtn">
                                <i class="fas fa-random"></i>
                            </button>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="phone" class="form-label">手机号</label>
                        <input type="tel" class="form-control" id="phone" name="phone">
                    </div>
                    <div class="mb-3">
                        <label for="email" class="form-label">邮箱</label>
                        <input type="email" class="form-control" id="email" name="email">
                    </div>
                    <div class="mb-3">
                        <label for="role" class="form-label">用户角色</label>
                        <select class="form-select" id="role" name="role">
                            <option value="user">普通用户</option>
                            <option value="admin">管理员</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-2"></i>
                        创建用户
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑用户模态框 -->
<div class="modal fade" id="editUserModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-user-edit me-2"></i>
                    编辑用户
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editUserForm">
                <div class="modal-body">
                    <input type="hidden" id="editUserId" name="user_id">
                    <div class="mb-3">
                        <label for="editUsername" class="form-label">用户名 *</label>
                        <input type="text" class="form-control" id="editUsername" name="username" required>
                    </div>
                    <div class="mb-3">
                        <label for="editPassword" class="form-label">新密码 <small class="text-muted">(留空保持不变)</small></label>
                        <div class="input-group">
                            <input type="password" class="form-control" id="editPassword" name="password" placeholder="留空保持不变">
                            <button class="btn btn-outline-secondary" type="button" onclick="togglePasswordVisibility('editPassword')">
                                <i class="fas fa-eye" id="editPasswordIcon"></i>
                            </button>
                            <button class="btn btn-outline-secondary" type="button" id="editGeneratePasswordBtn">
                                <i class="fas fa-random"></i>
                            </button>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="editPhone" class="form-label">手机号</label>
                        <input type="tel" class="form-control" id="editPhone" name="phone">
                    </div>
                    <div class="mb-3">
                        <label for="editEmail" class="form-label">邮箱</label>
                        <input type="email" class="form-control" id="editEmail" name="email">
                    </div>
                    <div class="mb-3">
                        <label for="editRole" class="form-label">用户角色</label>
                        <select class="form-select" id="editRole" name="role">
                            <option value="user">普通用户</option>
                            <option value="admin">管理员</option>
                        </select>
                    </div>
                    
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-2"></i>
                        保存更改
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 导入用户模态框 -->
<div class="modal fade" id="importUserModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-upload me-2"></i>
                    导入用户数据
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info">
                    <h6><i class="fas fa-info-circle me-2"></i>导入说明</h6>
                    <ul class="mb-0 small">
                        <li>支持CSV格式文件，编码为UTF-8</li>
                        <li>文件格式：用户名,密码,手机号,邮箱</li>
                        <li>第一行为标题行，将被忽略</li>
                        <li>用户名和密码为必填项</li>
                        <li>如果用户名已存在，将跳过该记录</li>
                    </ul>
                </div>
                
                <form id="importUserForm" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="importFile" class="form-label">选择CSV文件</label>
                        <input type="file" class="form-control" id="importFile" name="file" accept=".csv" required>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="skipDuplicates" name="skip_duplicates" checked>
                            <label class="form-check-label" for="skipDuplicates">
                                跳过重复的用户名
                            </label>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">CSV格式示例：</label>
                        <pre class="bg-light p-2 rounded small">用户名,密码,手机号,邮箱
user1,password123,13800138001,user1@example.com
user2,password456,13800138002,user2@example.com</pre>
                    </div>
                </form>
                
                <div id="importProgress" class="d-none">
                    <div class="progress mb-3">
                        <div class="progress-bar" role="progressbar" style="width: 0%"></div>
                    </div>
                    <div id="importStatus"></div>
                </div>
                
                <div id="importResult" class="d-none">
                    <h6>导入结果：</h6>
                    <div id="importSummary"></div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="startImport()" id="importBtn">
                    <i class="fas fa-upload me-2"></i>
                    开始导入
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteUserModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title text-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    确认删除用户
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>警告：</strong>此操作将永久删除用户及其所有相关数据，包括：
                    <ul class="mt-2 mb-0">
                        <li>用户的所有密码记录</li>
                        <li>用户的所有分享链接</li>
                        <li>相关的访问日志</li>
                    </ul>
                </div>
                <div id="deleteUserInfo" class="bg-light p-3 rounded">
                    <!-- 用户信息将在这里显示 -->
                </div>
                <div class="mt-3">
                    <label for="deleteConfirmText" class="form-label">请输入 <strong>DELETE</strong> 确认删除：</label>
                    <input type="text" class="form-control" id="deleteConfirmText" placeholder="输入 DELETE">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="confirmDeleteUser()" id="confirmDeleteBtn" disabled>
                    <i class="fas fa-trash me-2"></i>
                    确认删除
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    loadUsers();
    
    // 创建用户表单提交
    $('#createUserForm').on('submit', function(e) {
        e.preventDefault();
        createUser();
    });
    
    // 编辑用户表单提交
    $('#editUserForm').on('submit', function(e) {
        e.preventDefault();
        updateUser();
    });
    
    // 生成密码按钮
    $('#generatePasswordBtn').on('click', function() {
        generateRandomPassword('#password');
    });
    
    // 编辑时生成密码按钮
    $('#editGeneratePasswordBtn').on('click', function() {
        generateRandomPassword('#editPassword');
    });
    
    // 删除确认文本输入监听
    $('#deleteConfirmText').on('input', function() {
        const confirmBtn = $('#confirmDeleteBtn');
        if ($(this).val() === 'DELETE') {
            confirmBtn.prop('disabled', false);
        } else {
            confirmBtn.prop('disabled', true);
        }
    });
    
    function loadUsers() {
        $.ajax({
            url: '/api/users',
            method: 'GET',
            success: function(response) {
                const tbody = $('#usersTable tbody');
                tbody.empty();
                
                if (response.users.length === 0) {
                    tbody.append(`
                        <tr>
                            <td colspan="6" class="text-center text-muted py-4">
                                <i class="fas fa-users fa-2x mb-2"></i><br>
                                暂无用户数据
                            </td>
                        </tr>
                    `);
                    return;
                }
                
                response.users.forEach(function(user) {
                    const createdAt = new Date(user.created_at).toLocaleString('zh-CN');
                    tbody.append(`
                        <tr>
                            <!--<td>${user.id}</td>-->
                            <td>
                                <strong>${user.username}</strong>
                            </td>
                            <td>${user.phone || '-'}</td>
                            <td>${user.email || '-'}</td>
                            <td>
                                <span class="badge ${user.role === 'admin' ? 'bg-danger' : 'bg-primary'}">${user.role === 'admin' ? '管理员' : '用户'}</span>
                            </td>
                            <td>
                                <span class="badge ${user.is_active ? 'bg-success' : 'bg-secondary'}">${user.is_active ? '激活' : '禁用'}</span>
                            </td>
                            <td>${createdAt}</td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary me-1" onclick="editUser(${user.id})" title="编辑用户">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-sm ${user.is_active ? 'btn-outline-warning' : 'btn-outline-success'} me-1" 
                                        onclick="toggleUserStatus(${user.id}, ${!user.is_active})" 
                                        title="${user.is_active ? '禁用用户' : '启用用户'}">
                                    <i class="fas ${user.is_active ? 'fa-ban' : 'fa-check'}"></i>
                                </button>
                                <button class="btn btn-sm btn-outline-danger" onclick="deleteUser(${user.id})" title="删除用户">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                    `);
                });
            },
            error: function(xhr) {
                console.error('加载用户列表失败:', xhr);
                alert('加载用户列表失败');
            }
        });
    }
    
    function createUser() {
        const formData = new FormData($('#createUserForm')[0]);
        
        $.ajax({
            url: '/api/users',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                alert('用户创建成功！');
                $('#createUserModal').modal('hide');
                $('#createUserForm')[0].reset();
                loadUsers();
            },
            error: function(xhr) {
                const error = xhr.responseJSON?.detail || '创建用户失败';
                alert(error);
            }
        });
    }

    
    function generateRandomPassword(targetSelector) {
        $.ajax({
            url: '/api/generate-password',
            method: 'POST',
            data: {
                length: 12,
                use_numbers: true,
                use_letters: true,
                use_symbols: true
            },
            success: function(response) {
                $(targetSelector).val(response.password);
            },
            error: function(xhr) {
                console.error('生成密码失败:', xhr);
            }
        });
    }
    
    function updateUser() {
        const userId = $('#editUserId').val();
        const formData = new FormData($('#editUserForm')[0]);
        
        $.ajax({
            url: `/api/users/${userId}`,
            method: 'PUT',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                App.Utils.showAlert(response.message, 'success');
                $('#editUserModal').modal('hide');
                $('#editUserForm')[0].reset();
                loadUsers();
            },
            error: function(xhr) {
                const error = xhr.responseJSON?.detail || '更新用户失败';
                App.Utils.showAlert(error, 'error');
            }
        });
    }
    
    window.editUser = function(userId) {
        // 获取用户信息
        $.ajax({
            url: `/api/users/${userId}`,
            method: 'GET',
            success: function(response) {
                const user = response.user;
                $('#editUserId').val(user.id);
                $('#editUsername').val(user.username);
                $('#editPhone').val(user.phone || '');
                $('#editEmail').val(user.email || '');
                $('#editRole').val(user.role);
                $('#editIsActive').prop('checked', user.is_active == 1);
                $('#editPassword').val(''); // 清空密码字段
                $('#editUserModal').modal('show');
            },
            error: function(xhr) {
                const error = xhr.responseJSON?.detail || '获取用户信息失败';
                App.Utils.showAlert(error, 'error');
            }
        });
    };
    
    let currentDeleteUserId = null;
    
    // 切换用户状态
    window.toggleUserStatus = function(userId, newStatus) {
        const action = newStatus ? '启用' : '禁用';
        
        if (!confirm(`确定要${action}该用户吗？`)) {
            return;
        }
        
        $.ajax({
            url: `/api/users/${userId}/status`,
            method: 'PATCH',
            data: {
                is_active: newStatus
            },
            success: function(response) {
                App.Utils.showAlert(response.message, 'success');
                loadUsers(); // 重新加载用户列表
            },
            error: function(xhr) {
                const error = xhr.responseJSON?.detail || `${action}用户失败`;
                App.Utils.showAlert(error, 'error');
            }
        });
    };

    window.deleteUser = function(userId) {
        currentDeleteUserId = userId;
        
        // 获取用户信息用于显示
        $.ajax({
            url: `/api/users/${userId}`,
            method: 'GET',
            success: function(response) {
                const user = response.user;
                $('#deleteUserInfo').html(`
                    <div class="row">
                        <div class="col-sm-3"><strong>用户名：</strong></div>
                        <div class="col-sm-9">${user.username}</div>
                    </div>
                    <div class="row mt-2">
                        <div class="col-sm-3"><strong>手机号：</strong></div>
                        <div class="col-sm-9">${user.phone || '未设置'}</div>
                    </div>
                    <div class="row mt-2">
                        <div class="col-sm-3"><strong>邮箱：</strong></div>
                        <div class="col-sm-9">${user.email || '未设置'}</div>
                    </div>
                    <div class="row mt-2">
                        <div class="col-sm-3"><strong>创建时间：</strong></div>
                        <div class="col-sm-9">${new Date(user.created_at).toLocaleString('zh-CN')}</div>
                    </div>
                `);
                
                // 重置确认输入
                $('#deleteConfirmText').val('');
                $('#confirmDeleteBtn').prop('disabled', true);
                
                $('#deleteUserModal').modal('show');
            },
            error: function(xhr) {
                const error = xhr.responseJSON?.detail || '获取用户信息失败';
                App.Utils.showAlert(error, 'error');
            }
        });
    };
    
    window.confirmDeleteUser = function() {
        if (!currentDeleteUserId) return;
        
        $.ajax({
            url: `/api/users/${currentDeleteUserId}`,
            method: 'DELETE',
            success: function(response) {
                App.Utils.showAlert(response.message, 'success');
                $('#deleteUserModal').modal('hide');
                loadUsers();
                currentDeleteUserId = null;
            },
            error: function(xhr) {
                const error = xhr.responseJSON?.detail || '删除用户失败';
                App.Utils.showAlert(error, 'error');
            }
        });
    };
    
    window.exportUsers = function() {
        window.open('/api/export/users', '_blank');
    };
    
    window.startImport = function() {
        const fileInput = $('#importFile')[0];
        const file = fileInput.files[0];
        
        if (!file) {
            App.Utils.showAlert('请选择要导入的CSV文件', 'warning');
            return;
        }
        
        if (!file.name.toLowerCase().endsWith('.csv')) {
            App.Utils.showAlert('请选择CSV格式的文件', 'warning');
            return;
        }
        
        const formData = new FormData();
        formData.append('file', file);
        formData.append('skip_duplicates', $('#skipDuplicates').is(':checked'));
        
        // 显示进度条
        $('#importProgress').removeClass('d-none');
        $('#importResult').addClass('d-none');
        $('#importBtn').prop('disabled', true);
        
        // 模拟进度更新
        let progress = 0;
        const progressInterval = setInterval(function() {
            progress += Math.random() * 20;
            if (progress > 90) progress = 90;
            $('.progress-bar').css('width', progress + '%');
            $('#importStatus').text('正在处理文件...');
        }, 200);
        
        $.ajax({
            url: '/api/import/users',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                clearInterval(progressInterval);
                $('.progress-bar').css('width', '100%');
                $('#importStatus').text('导入完成');
                
                // 显示结果
                setTimeout(function() {
                    $('#importProgress').addClass('d-none');
                    $('#importResult').removeClass('d-none');
                    
                    const summary = `
                        <div class="alert alert-success">
                            <div class="row">
                                <div class="col-sm-6">成功导入：<strong>${response.success_count}</strong> 个用户</div>
                                <div class="col-sm-6">跳过重复：<strong>${response.skipped_count}</strong> 个用户</div>
                            </div>
                            <div class="row mt-2">
                                <div class="col-sm-6">失败记录：<strong>${response.error_count}</strong> 个</div>
                                <div class="col-sm-6">总计处理：<strong>${response.total_count}</strong> 个</div>
                            </div>
                        </div>
                    `;
                    
                    if (response.errors && response.errors.length > 0) {
                        const errorList = response.errors.map(error => 
                            `<li>第${error.row}行: ${error.message}</li>`
                        ).join('');
                        summary += `
                            <div class="alert alert-warning">
                                <h6>错误详情：</h6>
                                <ul class="mb-0">${errorList}</ul>
                            </div>
                        `;
                    }
                    
                    $('#importSummary').html(summary);
                    
                    if (response.success_count > 0) {
                        loadUsers(); // 重新加载用户列表
                    }
                }, 500);
            },
            error: function(xhr) {
                clearInterval(progressInterval);
                $('#importProgress').addClass('d-none');
                
                const error = xhr.responseJSON?.detail || '导入失败';
                App.Utils.showAlert(error, 'error');
            },
            complete: function() {
                $('#importBtn').prop('disabled', false);
            }
        });
    };
});
function togglePasswordVisibility(fieldId) {
    const field = document.getElementById(fieldId);
    const icon = document.getElementById(fieldId + 'Icon');

    if (field.type === 'password') {
        field.type = 'text';
        icon.className = 'fas fa-eye-slash';
    } else {
        field.type = 'password';
        icon.className = 'fas fa-eye';
    }
}
</script>
{% endblock %}